"""LLM API integration module for chat functionality"""
import requests
import json
import logging

class Chat:
    """Chat class for handling LLM API interactions"""

    API_URL = "https://api.siliconflow.cn/v1/chat/completions"
    MODEL_NAME = "Qwen/Qwen2.5-72B-Instruct-128K"

    def __init__(self, api_key, prompt):
        """Initialize Chat instance with API key and system prompt

        Args:
            api_key (str): The API key for authentication
            prompt (str): The system prompt to guide the conversation
        """
        self.api_key = api_key
        self.system_prompt = prompt
        self.chat_history = {}

    def chat(self, user_message, user_id="default"):
        """Send a message to the LLM and get the response

        Args:
            user_message (str): The user's input message
            user_id (str, optional): Unique identifier for the user. Defaults to "default"

        Returns:
            str: The model's response message
        """
        # 初始化新用户的对话历史
        if user_id not in self.chat_history:
            self.chat_history[user_id] = []

        # 构建消息列表
        messages = [
            {"role": "system", "content": self.system_prompt}
        ] + self.chat_history[user_id] + [
            {"role": "user", "content": user_message}
        ]

        # 准备请求数据
        payload = {
            "model": self.MODEL_NAME,
            "messages": messages,
            "stream": False,
            "max_tokens": 512,
            "stop": ["null"],
            "temperature": 0.7,
            "top_p": 0.7,
            "top_k": 50,
            "frequency_penalty": 0.5,
            "n": 1,
            "response_format": {"type": "text"},
            "tools": [{
                "type": "function",
                "function": {
                    "description": "<string>",
                    "name": "<string>",
                    "parameters": {},
                    "strict": False
                }
            }]
        }

        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }

        try:
            response = requests.post(self.API_URL, json=payload, headers=headers)
            response.raise_for_status()
            res_obj = response.json()

            if res_obj.get("code") == 50501:
                logging.warning("API request timeout")
                return "模型请求超时，请稍后再试"

            content = res_obj['choices'][0]['message']['content']

            # 更新对话历史
            self.chat_history[user_id].extend([
                {"role": "user", "content": user_message},
                {"role": "assistant", "content": content}
            ])

            # 保持历史记录在合理范围内（最近10轮对话）
            if len(self.chat_history[user_id]) > 20:
                self.chat_history[user_id] = self.chat_history[user_id][-20:]

            logging.info(f"Successfully generated response for user {user_id}")
            return content

        except requests.exceptions.RequestException as e:
            logging.error(f"API request failed: {str(e)}")
            return "抱歉，网络连接出现问题，请稍后再试"

        except (KeyError, json.JSONDecodeError) as e:
            logging.error(f"Failed to parse API response: {str(e)}")
            return "抱歉，服务器返回了无效的响应，请稍后再试"

        except Exception as e:
            logging.error(f"Unexpected error: {str(e)}")
            return "抱歉，我现在无法回复，请稍后再试"